package org.geektimes.projects.user.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.geektimes.projects.user.web.model.GiteeConstants;
import org.geektimes.projects.user.web.model.ThridUserInfo;
import org.geektimes.web.mvc.controller.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2021/4/19 20:26
 */
@Path("/gitee")
public class GiteeController implements RestController {


    String giteeUrlPath = "https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s";


    @GET
    @POST
    @Path("/enter") // /hello/world -> HelloWorldController
    public Object enter(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        String code = request.getParameter("code");
        String token = getToken(code);

        ThridUserInfo userInfo = getThridUserInfo(token);

        return userInfo;
    }


    private String getToken(String code) throws UnsupportedEncodingException {
        String callbackUrl = URLEncoder.encode(GiteeConstants.callbackUrl, "UTF-8");
        String urlPath = String.format(giteeUrlPath, code, GiteeConstants.clientId, callbackUrl, GiteeConstants.clientSecret);

        Client client = ClientBuilder.newClient();
        Response giteeResponse = client
                .target(urlPath)      // WebTarget
                .request() // Invocation.Builder
                .post(null);                                     //  Response


        System.out.println("status =>" + giteeResponse.getStatus());

        String content = giteeResponse.readEntity(String.class);
        System.out.println(" content " + content);

        JSONObject jsonObject = JSON.parseObject(content);

        return jsonObject.getString("access_token");
    }


    private ThridUserInfo getThridUserInfo(String token) {
        String urlPath = "https://gitee.com/api/v5/user?access_token=" + token;

        Client client = ClientBuilder.newClient();
        Response giteeResponse = client
                .target(urlPath)      // WebTarget
                .request() // Invocation.Builder
                .get();                                     //  Response

        System.out.println("status =>" + giteeResponse.getStatus());

        String content = giteeResponse.readEntity(String.class);
        System.out.println(" user info =>  " + content);

        ThridUserInfo thridUserInfo = JSONObject.parseObject(content, ThridUserInfo.class);
        return thridUserInfo;
    }


}
